import { View, Text } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { useState, useEffect, useLayoutEffect } from 'react'
import Loading from '../component/load'
import Main from '../main'
import Utils from '../../../utils/index'
import { getStorage } from '../../components/utils'
import { getBaseUrl, requestSystemUrl } from '../../../network/baseUrl'
import { HttpGet } from '../../../network/servers'
import md5 from 'md5'
import { connect, useDispatch } from 'react-redux'

import './index.scss'

const storage = getStorage()

function App() {

    const [init, setInit] = useState(false)
    const dispatch = useDispatch()

    const getToken = () => {
        if (Utils.getQueryVariable('env') === 'weapp') {
            return Utils.getQueryVariable('lg_tk')
        } else {
            return storage.get('token') || Utils.getQueryVariable('lg_tk')
        }
    }

    // 获取初始数据
    const getCommonData = async (params) => {
        if (process.env.TARO_ENV === 'h5') {
            Taro.getSysWeb({ sysId: '260', schoolId: Utils.getQueryVariable('schoolId') }, 'web', function (res) {
                if (res) {
                    dispatch({ type: 'SET_ISMANAGE', data: (Utils.getQueryVariable('isManage') == '1' ? 1 : 0) })
                    console.log(res, 'res');
                    let MainServerAddr = res
                    //做掉线检测
                    if (!sessionStorage.getItem("noFirst") && process.env.TARO_ENV === 'h5') {
                        let script = document.createElement("script");
                        script.src = MainServerAddr + "/JS/mobile-check-online.min.js";
                        script.type = "text/javascript";
                        let token = getToken()
                        script.onload = function () {
                            lgCheckOnline(MainServerAddr, token, "200");
                        }
                        document.getElementsByTagName("head")[0].appendChild(script);
                        sessionStorage.setItem("noFirst", String(true));
                    }
                    HttpGet({   //用户信息
                        // url: MainServerAddr + 'api/commons/school/user/self',
                        url: MainServerAddr + `api/common/user`,
                        data: {
                            token: Utils.getQueryVariable('lg_tk')
                        }
                    }).then((res1) => {
                        console.log('8888')
                        HttpGet({   //用户信息
                            url: MainServerAddr + 'api/common/system/info',
                        }).then((res2) => {
                            dispatch({ type: 'SET_SYSTEMINFO', data: res2.data })
                            setInit(true)
                            // 2023-09-14 适配高级管理员 start
                            let identityList = res1.data.identityList;
                            let identity = identityList.find(item => item.identityCode === Utils.getQueryVariable('lg_ic'))
                            if (identity?.advanced == 1) {
                                dispatch({ type: 'SET_ADVANCEDADMIN', data: 1 })
                            } else {
                                dispatch({ type: 'SET_ADVANCEDADMIN', data: 0 })
                            }
                            // 2023-09-14 适配高级管理员 end
                        })
                        dispatch({ type: 'SET_USERINFO', data: res1.data })
                        // Taro.getSysWeb({ sysId: '220' }, 'web', function (data) {
                        //     dispatch({ type: 'SET_NOTICEADDR', data })
                        // })
                    })
                }
            })
        } else {
            let userInfo = JSON.parse(storage.get('userInfo'))
            dispatch({ type: 'SET_USERINFO', data: userInfo })
            Taro.getSysWeb({ sysId: '260', schoolId: userInfo.SchoolID }, 'web', function (data) {
                dispatch({ type: 'SET_NOTICEADDR', data })
            })
        }
    }

    useLayoutEffect(() => {
        // document.title = '周行事历'
        let router = Taro.getCurrentInstance().router;
        let routerParams = router ? router.params : {};

        let params = {
        } as any


        if (process.env.TARO_ENV === 'h5') {
            if (Utils.getQueryVariable('env') === 'weapp') {  //内嵌进h5的页面
                dispatch({ type: 'SET_ENV', data: 'weapp' })

                requestSystemUrl('260').then((res) => {
                    // console.log(res,'res11');
                    console.log(res,'res')
                    window.baseUrl = res
                    params = {
                        lg_tk: Utils.getQueryVariable("lg_tk") || storage.get('lg_tk'),
                        lg_ic: Utils.getQueryVariable("lg_ic"),
                        env: Utils.getQueryVariable('env'),
                        schoolId: Utils.getQueryVariable('schoolId'),
                        baseUrl: res
                    }
                    dispatch({ type: 'SET_BASEURL', data: res })
                    dispatch({ type: 'SET_TOKEN', data: getToken() })
                    dispatch({ type: 'SET_IDENTITYCODE', data: params.lg_ic })
                    getCommonData(params)
                })
            } else {
                window.baseUrl = getBaseUrl()
                console.log(window.baseUrl)
                dispatch({ type: 'SET_ENV', data: 'app' })
                dispatch({ type: 'SET_BASEURL', data: getBaseUrl() })
                params = {
                    lg_tk: storage.get('lg_tk') || Utils.getQueryVariable("lg_tk"),
                    lg_ic: storage.get('lg_ic') || Utils.getQueryVariable("lg_ic"),
                    baseUrl: getBaseUrl()
                }
                dispatch({ type: 'SET_TOKEN', data: getToken() })
                dispatch({ type: 'SET_IDENTITYCODE', data: params.lg_ic })
                getCommonData(params)
            }
        } else {
            dispatch({ type: 'SET_ENV', data: 'weapp' })
            dispatch({ type: 'SET_BASEURL', data: getBaseUrl() })
            params = {
                lg_tk: storage.get('lg_tk'),
                lg_ic: storage.get('lg_ic'),
                baseUrl: getBaseUrl()
            }
            getCommonData(params)
        }
    }, [])

    useEffect(() => {
        const getInWebview = () => {
            return Utils.getQueryVariable('env') === 'weapp' || window.__wxjs_environment === 'miniprogram'
        }

        Taro.getInWebview = getInWebview
    }, [])

    if (!init) {
        return (
            <View>
                <Loading content='加载中' isOpened={true} />
            </View>
        )
    }

    return (
        <Main />
    )
}
export default App